<template>
  <a-card class="general-card" title="拼团活动" :bordered="false">
    <a-tabs @change="(val)=>{apiParams.promotionStatus = val}" :default-active-key="pintuanStatus">
      <a-tab-pane key="NEW" title="未开始"></a-tab-pane>
      <a-tab-pane key="START" title="已开始"></a-tab-pane>
      <a-tab-pane key="END" title="已结束"></a-tab-pane>
      <a-tab-pane key="CLOSE" title="已关闭"></a-tab-pane>
    </a-tabs>
    <searchTable
      :columns="columnsSearch"
      time-type="timestamp"
      @reset="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
      @search="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
    ></searchTable>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="newAct"> 添加 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <tablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getPintuanList"
      :api-params="apiParams"
      :bordered="true"
    >
      <template #time="{ data }"
        >{{ data.startTime }}<span style="margin: 0 10px">-</span
        >{{ data.endTime }}</template
      >
      <template #btnList="{ data }">
        <a-space>
          <a-button
            v-if="data?.promotionStatus == 'NEW'"
            type="text"
            status="warning"
            @click="edit(data)"
          >
            编辑</a-button
          >
          <a-button
            v-if="
              data?.promotionStatus !== 'NEW' &&
              data?.promotionStatus !== 'CLOSE'
            "
            type="text"
            status="success"
            @click="manage(data, 'view')"
            >查看</a-button
          >
          <a-button
            v-if="data.promotionStatus == 'NEW'"
            type="text"
            @click="manage(data, 'manager')"
            >管理</a-button
          >
          <a-button
            v-if="data?.promotionStatus != 'START'"
            type="text"
            status="danger"
            @click="remove(data)"
          >
            删除</a-button
          >
          <a-button
            v-if="data.promotionStatus === 'START'"
            type="text"
            status="danger"
            @click="openOrClose(data)"
          >
            关闭
          </a-button>
          <a-button
            v-if="data.promotionStatus === 'CLOSE'"
            type="text"
            status="success"
            @click="openOrClose(data)"
          >
            开启
          </a-button>
        </a-space>
      </template>
    </tablePage>
  </a-card>
</template>

<script setup lang="ts">
  import {
    deletePintuan,
    editPintuanStatus,
    getPintuanList,
  } from '@/api/promotion';
  import searchTable from '@/components/search-column/index.vue';
  import tablePage from '@/components/table-pages/index.vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { ColumnsDataRule, MethodsRule, SearchRule } from '@/types/global';
  import { promotionStatus, promotionStatusSelect } from '@/utils/tools';
  import { Message } from '@arco-design/web-vue';
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const tablePageRef = ref<any>();
  const pintuanStatus = ref<string>('START');
  const apiParams = ref<any>({ sort: 'startTime',promotionStatus:pintuanStatus.value });
  const router = useRouter();
  const columnsSearch: Array<SearchRule> = [
    {
      label: '活动名称',
      model: 'promotionName',
      disabled: false,
      input: true,
    },

    {
      label: '活动时间',
      model: 'selectDate',
      disabled: false,
      datePicker: {
        type: 'range',
      },
    },
  ];

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '活动名称',
      dataIndex: 'promotionName',
    },
    {
      title: '活动时间',
      dataIndex: 'time',
      width: 400,
      slot: true,
      slotTemplate: 'time',
    },

    {
      title: '状态',
      dataIndex: 'promotionStatus',
      slot: true,
      slotData: {
        badge: promotionStatus,
      },
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 250,
    methods: [
      {
        slot: true,
        slotTemplate: 'btnList',
      },
    ],
  };
  // 新增拼团活动
  const newAct = () => {
    router.push({
      name: 'pintuan-edit',
    });
  };
  // 编辑拼团活动
  const edit = (data: any) => {
    router.push({
      name: 'pintuan-edit',
      query: { id: data.id },
    });
  };
  // 删除拼团活动
  const remove = (val: any) => {
    modal.confirm({
      title: '确认删除',
      content: '您确认要删除此拼团活动？',
      alignCenter: false,
      onOk: async () => {
        deletePintuan(val.id).then((res: any) => {
          if (res.data.success) {
            Message.success('删除成功');
            tablePageRef.value.init();
          }
        });
      },
    });
  };
  // 关闭或开启拼团活动
  const openOrClose = (data: any) => {
    let name = '开启';
    if (data.promotionStatus == 'START') {
      name = '关闭';
      modal.confirm({
        title: '提示',
        content: `确认${name}此活动吗?需要一定时间才能生效，请耐心等待`,
        alignCenter: false,
        onOk: async () => {
          const res = await editPintuanStatus(data.id);
          if (res.data.success) {
            Message.success(`${name}成功`);
            tablePageRef.value.init();
          }
        },
      });
    } else {
      const sTime = new Date();
      sTime.setMinutes(sTime.getMinutes() + 10);
      const eTime = new Date(
        new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1
      );
      const params = {
        startTime: sTime.getTime(),
        endTime: eTime.getTime(),
      };
      modal.confirm({
        title: '确认开启(默认为当前时间的十分钟之后)',
        content: `您确认要开启此拼团活动?`,
        alignCenter: false,
        onOk: async () => {
          const res = await editPintuanStatus(data.id, params);
          if (res.data.success) {
            Message.success(`开启活动成功`);
            tablePageRef.value.init();
          }
        },
      });
    }
  };
  // 查看,管理拼团活动
  const manage = (data: any, state: any) => {
    router.push({
      name: 'pintuan-goods',
      query: { id: data.id, status: state },
    });
  };
</script>
